Ext.define('cfWeb.cfWebComponent.NavView', {
    extend: 'Ext.view.View',
    alias: 'widget.navView',
    id: 'navView',
    layout: 'border',
    height: 56,
    selfId: undefined,
    userName: undefined,
    userImg: undefined,
    title: undefined,
    menu: [],
    tpl: undefined,
    tarNav: 'index',
    temp1: [
        '<div class="cf_nav clearfix">',
        '<div class="cf_logo left_width">',
        '<span class="logo_sign"></span>'
    ],
    temp2: [
        '</div><ul class="cf_navlist">',
        '<tpl for=".">',
        '<li class="{[xindex === 1 ? " on" : ""]} navigation-item " data-target="{navTarget}">',
        '<a>{navName}</a>',
        '</li>',
        '</tpl>',
        '</ul>',
        '<div class="navOverflow dis_n" data-count="0"><span class="icon-arrow-down3 downArrow"></span>',
        '<div class="pulldown nav_pulldown">',
        '<div class="setting_list_arrow">',
        '</div>',
        '<ul class="pulldownlist">',
        '<tpl for=".">',
        '<li class="{[xindex === 1 ? " on" : ""]} navigation-item " data-target="{navTarget}">',
        '<a>{navName}</a>',
        '</li>',
        '</tpl>',
        '</ul>',
        '</div>',
        '</div>',
        '<div class="cf_nav_action ">',
    //			'<div class="copyRightContent">Copyright ©2014 Zfoundry</div>',
    // '<div class="cf_language self_border_right">',
    // '<div class="lang_bkg">',
    // '<div class="lang_sign switch_on" id="ls_button">English</div>',
    // '</div></div>'
    ],
    temp3: [
        '<div class="cf_account_setting">',
        '<div class="setting_wrap clearfix">',
        '<div class="avatar_head">',
        '<img src="resources/img/avatar.jpeg" width="40" height="40" />',
        '<div class="avatar_mask"></div>',
        '<span class="noti_count"></span></div>',
        '<div class="avatar_name"></div></div>',
        '<div class="setting_pulldown">',
        '<div class="setting_list_arrow"></div>',
        '<ul class="setting_list">'
    ],
    temp4: [
        '</ul></div></div>',
    // '<div class="change_org_space_wrap"><div class="orgchange" style="float:left;"><span>',
    // cfWebLang.Util.Organization,
    // ':</span><div class="org_wrap"><select name="selectOrg" id="selectOrg" old_value=""></select><span class="icon-arrow-down3"></span></div></div>',
    // '<div class="spacechange"><span>',
    // cfWebLang.Util.Space,
    // ':</span><div class="space_wrap"><select name="selectSpace" id="selectSpace" old_value=""></select><span class="icon-arrow-down3"></span></div></div></div></div></div>',
    ],
    // org: Ext.create('cfWeb.store.appManage.OrgStore'),
    // space: Ext.create('cfWeb.store.appManage.SpaceStore'),
    // orgOnChange: function(defaultspace, first) {
    //     var orgName = Ext.fly('selectOrg').getValue();
    //     var oldValue = Ext.fly('selectOrg').getAttribute('old_value');
    //     var me = this;
    //     this.space.load({
    //         params: {
    //             orgName: orgName
    //         },
    //         callback: function(records) {
    //             console.log(records);
    //             /*if(records.length==0){
    //             	var orgOptions = Ext.get('selectOrg').dom.options;
    //             	 for(var i = 0 ; i<orgOptions.length;i++){
    //             		  if(orgOptions[i].value==oldValue){
    //                     	orgOptions[i].selected="selected";
    //                     	break;
    //             		  }
    //             	  }
    //             	Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Util.SpaceUnexit);
    //             	return;
    //             }*/
    //             Ext.get('selectOrg').set({
    //                 old_value: orgName
    //             });
    //             Ext.fly('selectSpace').setHTML('');
    //             var spaceOption = '<option value="" style="display:none;"></option>';
    //             Ext.fly('selectSpace').insertHtml('beforeEnd', spaceOption);
    //             this.each(function(i) {
    //                 spaceOption = '<option value="' + i.get('name') + '">' + i.get('name') + '</option>';
    //                 Ext.fly('selectSpace').insertHtml('beforeEnd', spaceOption);
    //             });
    //             var spaceOptions = Ext.get('selectSpace').dom.options;
    //             if (first == true) {
    //                 if (defaultspace == null || defaultspace == '') {
    //                     spaceOptions[0].selected = 'selected';
    //                 }
    //                 for (var i = 0; i < spaceOptions.length; i++) {
    //                     if (spaceOptions[i].value == defaultspace) {
    //                         spaceOptions[i].selected = 'selected';
    //                         break;
    //                     }
    //                 }
    //             } else {
    //                 if (spaceOptions.length > 1) {
    //                     spaceOptions[1].selected = 'selected';
    //                 }
    //                 me.spaceOnChange();
    //             }
    //         }
    //     });
    // },
    //
    // spaceOnChange: function() {
    //     //请求重新登录
    //     var space = Ext.get('selectSpace').getValue();
    //     var org = Ext.get('selectOrg').getValue();
    //     var oldOrg = Ext.fly('selectOrg').getAttribute('old_value');
    //     var oldSpace = Ext.fly('selectSpace').getAttribute('old_value');
    //     Ext.Ajax.request({
    //         url: 'rest/login/checkLogin',
    //         method: 'GET',
    //         params: {
    //             org: org,
    //             space: space,
    //             oldOrg: oldOrg,
    //             oldSpace: oldSpace
    //         },
    //         success: function(response) {
    //             Ext.get('selectSpace').set({
    //                 old_value: space
    //             });
    //             var obj = Ext.JSON.decode(response.responseText);
    //             if (obj.data.logined == false) {
    //                 Ext.get('error').dom.style.display = '';
    //             } else {
    //                 window.location = './index.html';
    //             }
    //         },
    //         failure: function(response) {
    //             var orgOptions = Ext.get('selectOrg').dom.options;
    //             for (var i = 0; i < orgOptions.length; i++) {
    //                 if (orgOptions[i].value == oldOrg) {
    //                     orgOptions[i].selected = 'selected';
    //                     break;
    //                 }
    //             }
    //             var spaceOptions = Ext.get('selectSpace').dom.options;
    //             for (var i = 0; i < spaceOptions.length; i++) {
    //                 if (spaceOptions[i].value == oldSpace) {
    //                     spaceOptions[i].selected = 'selected';
    //                     break;
    //                 }
    //             }
    //             var obj = Ext.JSON.decode(response.responseText);
    //             if (obj.data != null && obj.data.source == 1) {
    //                 Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, obj.data.message);
    //             } else if (obj.data != null && obj.data.source != 1) {
    //                 Ext.MessageBox.alert(cfWebLang.ErrorSource.app, cfWebLang.Error.SystemError);
    //             } else {
    //                 Ext.MessageBox.alert(cfWebLang.ErrorSource.app, cfWebLang.Error.SystemError);
    //             }
    //         }
    //     });
    // },

    initComponent: function() {
        this.argsInit();
        this.tplInit();
        this.addEvents({
            //事件
            'onNavChange': true,
            'onMenuClicked': true,
            'onLanguageChange': true,
            'orgOnChange': true,
            'spaceOnChange': true
        });
        this.callParent(arguments);
    },

    tplInit: function() {
        var title = '<span class="logo_title">' + this.title + '</span>';
        this.temp1.push(title);
        var menu = '';
        var lth = this.menu.length;
        for (var i = 0; i < lth; i++) {
            menu += '<li data-id="' + this.menu[i].id + '">' + this.menu[i].name + '<span class="count"></span></li>';
        }
        this.temp3.push(menu);

        this.tpl = this.temp1.concat(this.temp2, this.temp3, this.temp4);
    //		console.log(this.tpl);
    },

    argsInit: function() {
        if (!this.title) {
            this.title = '';
        }
    },
    listeners: {
        viewready: function(me) {
            this.selfId = this.getEl().id;
            this.setUser(this.userName, this.userImg);

            // var org = Ext.get('selectOrg');
            //
            // org.on('change', this.orgOnChange, this);
            //
            // var space = Ext.get('selectSpace');
            // space.on('change', this.spaceOnChange, this);

            var nav = Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist li');
            nav.on('click', this.onNavChange, this);
            var info = Ext.select('div[id=\'' + this.selfId + '\'] div.copyRight');
            info.on('click', this.showCopyRight, this);

            var expNav = Ext.select('div[id=\'' + this.selfId + '\'] ul.pulldownlist li');
            expNav.on('click', this.onNavChange, this);

            // var langButton = Ext.select('div[id=\'' + this.selfId + '\'] div#ls_button');
            // langButton.on('click', this.languageSwitch, this);

            var settingButton = Ext.select('div[id=\'' + this.selfId + '\'] ul.setting_list li');
            settingButton.on('click', this.onMenuClicked, this);
            this.setNav(this.tarNav);
            this.on('resize', this.widthAdj, this);
            this.widthAdj(me);
        },

    },
    widthAdj: function(me) {
        var wrapWidth = me.getWidth();
        var title = Ext.select('div[id=\'' + this.selfId + '\'] div.cf_logo');
        var nav = Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist');
        var expand = Ext.select('div[id=\'' + this.selfId + '\'] div.navOverflow');
        var action = Ext.select('div[id=\'' + this.selfId + '\'] div.cf_nav_action ');
        var menuBlock = Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist li.navigation-item');
        var expMenuBlock = Ext.select('div[id=\'' + this.selfId + '\'] ul.pulldownlist li.navigation-item');

        var titleWidth = title.elements[0].offsetWidth;
        var navWidth = nav.elements[0].offsetWidth;
        var expandWidth = expand.elements[0].offsetWidth;
        var actionWidth = action.elements[0].offsetWidth;
        var blockWidth = menuBlock.elements[0].offsetWidth;
        var total = titleWidth + navWidth + expandWidth + actionWidth;


        var _changeMenu = function(opt, num) {
            var dis_now = parseInt(expand.elements[0].getAttribute('data-count')); //当前expblock显示的个数
            console.log(dis_now);
            var lth = menuBlock.elements.length;
            console.log(lth);
            if (opt < 0) {
                expand.removeCls('dis_n');
                var total = dis_now + num;
                console.log(total);
                menuBlock.removeCls('dis_n'); //重置menu块
                expMenuBlock.addCls('dis_n');
                var start;
                if (total <= lth) {
                    start = lth - total;
                    expand.elements[0].setAttribute('data-count', total);
                } else {
                    start = 0;
                    expand.elements[0].setAttribute('data-count', lth);
                }
                for (var i = start; i < lth; i++) {
                    menuBlock.elements[i].className = menuBlock.elements[i].className + ' dis_n';
                    expMenuBlock.elements[i].className = expMenuBlock.elements[i].className.replace(' dis_n', '');
                }

            } else if (opt > 0) {
                expand.addCls('dis_n');
                menuBlock.removeCls('dis_n'); //重置menu块
                expMenuBlock.addCls('dis_n');
                if (num <= dis_now) {
                    var total = dis_now - num;
                    var start = lth - total;
                    for (var i = start; i < lth; i++) {
                        menuBlock.elements[i].className = menuBlock.elements[i].className + ' dis_n';
                        expMenuBlock.elements[i].className = expMenuBlock.elements[i].className.replace(' dis_n', '');
                    }
                    expand.elements[0].setAttribute('data-count', total);
                } else {
                    expand.elements[0].setAttribute('data-count', 0);
                }
            }
        };
        var _updateWidth = function() {
            titleWidth = title.elements[0].offsetWidth;
            navWidth = nav.elements[0].offsetWidth;
            expandWidth = expand.elements[0].offsetWidth;
            actionWidth = action.elements[0].offsetWidth;
            blockWidth = menuBlock.elements[0].offsetWidth;
            total = titleWidth + navWidth + expandWidth + actionWidth;
        };
        var adjMain = function() {

            if (total >= wrapWidth) { //缩小
                if (action.elements[0].className.indexOf('medium') > 0) {
                    action.removeCls('medium').addCls('small');
                    _updateWidth();
                    if (total >= wrapWidth) {
                        adjMain();
                    }
                } else if (action.elements[0].className.indexOf('small') > 0) {

                    var lth = menuBlock.elements.length;
                    var number = Math.ceil((total - wrapWidth) / blockWidth);
                    _changeMenu(-1, number);
                } else {
                    action.addCls('medium');
                    _updateWidth();
                    if (total >= wrapWidth) {
                        adjMain();
                    }
                }
            } else { //扩大
                var dis_now = parseInt(expand.elements[0].getAttribute('data-count'));
                if (dis_now > 0) {
                    var num = Math.ceil((wrapWidth - total) / blockWidth);
                    if (num <= dis_now) {
                        (1, num);
                        _updateWidth();
                        adjMain();
                    } else {
                        _changeMenu(1, dis_now);
                        _updateWidth();
                        adjMain();
                    }
                } else {
                    if (action.elements[0].className.indexOf('small') > 0) {
                        action.removeCls('small').addCls('medium');
                        _updateWidth();
                        adjMain();
                    } else if (action.elements[0].className.indexOf('medium') > 0) {
                        action.removeCls('medium');
                        _updateWidth();
                        adjMain();
                    }
                }
            }
        };
        adjMain();
    },
    getTarNode: function(tar, tag) {
        console.log(tar.tagName);
        if (tar.tagName == undefined) {
            return false;
        }
        var res = tar.getAttribute(tag);
        if (res != null && res.length > 0) {
            return tar;
        } else {
            return this.getTarNode(tar.parentNode, tag);
        }
    },
    showCopyRight: function() {
        var acts = Ext.select('div[id=\'' + this.selfId + '\'] div.cf_nav_action').elements[0];
        acts.setAttribute('style', 'opacity:0;');
        var copyright = Ext.select('div[id=\'' + this.selfId + '\'] div.copyRightContent').elements[0];
        copyright.setAttribute('style', 'opacity:1;');

        setTimeout(function() {
            copyright.setAttribute('style', 'opacity:0;');
            acts.setAttribute('style', 'opacity:1;');
        }, 3000);
    },
    onNavChange: function(a, b) {
        var tar = this.getTarNode(b, 'data-target');
        var target = tar.getAttribute('data-target');
        if (tar.className.indexOf(' on ') < 0) {
            var on = Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist li.on');
            var expOn = Ext.select('div[id=\'' + this.selfId + '\'] ul.pulldownlist li.on');
            on.removeCls('on');
            expOn.removeCls('on');
            Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist li[data-target=\'' + target + '\']').addCls('on');
            Ext.select('div[id=\'' + this.selfId + '\'] ul.pulldownlist li[data-target=\'' + target + '\']').addCls('on');
            this.fireEvent('onNavChange', tar, target, this);
        }
    },
    onMenuClicked: function(e, dom) {
        var li = this.getTarNode(dom, 'data-id');
        var dataId = li.getAttribute('data-id');
        this.fireEvent('onMenuClicked', dataId);
    },
    //方法
    setMessageCount: function(count) {
        var number = parseInt(count);
        if (isNaN(number)) {
            return this;
        } else {
            var num = Ext.select('div[id=\'' + this.selfId + '\'] span[class=\'noti_count\']');
            var num2 = Ext.select('div[id=\'' + this.selfId + '\'] li[data-id=\'message\'] span');
            if (number == 0) {
                num.elements[0].innerHTML = 0;
                num.hide();
                num2.elements[0].innerHTML = '';
            } else {
                num.elements[0].innerHTML = number;
                num.show();
                num2.elements[0].innerHTML = '(' + number + ')';
            }
            return this;
        }
    },
    getMessageCount: function() {
        var num = Ext.select('div[id=\'' + this.selfId + '\'] span[class=\'noti_count\']');
        var count = num.elements[0].innerHTML;
        count = parseInt(count);
        return count;
    },
    getUser: function() {
        return this.userName;
    },
    setUser: function(userName, imgUrl) {
        var name = Ext.select('div[id=\'' + this.selfId + '\'] div[class=\'avatar_name\']').elements[0];
        var img = Ext.select('div[id=\'' + this.selfId + '\'] div[class=\'avatar_head\'] img').elements[0];
        if (name && img) {
            if (imgUrl) {
                img.src = imgUrl;
            }
            if (userName) {
                name.innerHTML = userName;
            }
        }
        this.userName = userName;
        this.userImg = imgUrl;
        return this;
    },
    setNav: function(tar) {
        var on = Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist li.on');
        var expOn = Ext.select('div[id=\'' + this.selfId + '\'] ul.pulldownlist li.on');
        on.removeCls('on');
        expOn.removeCls('on');

        var now = Ext.select('div[id=\'' + this.selfId + '\'] ul.cf_navlist li[data-target=\'' + tar + '\']').elements[0];
        var expNow = Ext.select('div[id=\'' + this.selfId + '\'] ul.pulldownlist li[data-target=\'' + tar + '\']').elements[0];

        expNow.className = expNow.className + ' on';
        now.className = now.className + ' on ';
    },
    // setDefaultOrgSpace: function(org, space) {
    //     Ext.get('selectOrg').dom.value = org;
    //     /*this.orgOnChange();*/
    //     Ext.get('selectSpace').dom.value = space;
    // },
    // getOrgSpace: function() {
    //     var org = Ext.select('div[id=\'' + this.selfId + '\'] #selectOrg').elements[0].value;
    //     var space = Ext.select('div[id=\'' + this.selfId + '\'] #selectSpace').elements[0].value;
    //     return {
    //         org: org,
    //         space: space
    //     };
    // }

});
